package com.example.myapplication1;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsControllerCompat;

import com.example.myapplication1.db.DatabaseHelper;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputLayout;
import com.google.android.material.textfield.TextInputEditText;

public class ForgotPasswordActivity extends AppCompatActivity {
    private TextInputLayout usernameLayout;
    private TextInputLayout phoneLayout;
    private TextInputLayout newPasswordLayout;
    private TextInputLayout confirmPasswordLayout;
    private TextInputEditText usernameInput;
    private TextInputEditText phoneInput;




    private TextInputEditText newPasswordInput;
    private TextInputEditText confirmPasswordInput;
    private MaterialButton resetButton;
    private View loadingProgress;
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 设置状态栏
        setupStatusBar();
        
        setContentView(R.layout.activity_forgot_password);

        initViews();
        setupToolbar();
        setupClickListeners();
    }

    private void setupStatusBar() {
        // 设置状态栏为透明
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.primary_lightest, null));
        
        // 设置状态栏图标为深色
        WindowInsetsControllerCompat windowInsetsController =
                WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView());
        windowInsetsController.setAppearanceLightStatusBars(true);
    }

    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        usernameLayout = findViewById(R.id.usernameLayout);
        phoneLayout = findViewById(R.id.phoneLayout);
        newPasswordLayout = findViewById(R.id.newPasswordLayout);
        confirmPasswordLayout = findViewById(R.id.confirmPasswordLayout);
        usernameInput = findViewById(R.id.usernameInput);
        phoneInput = findViewById(R.id.phoneInput);
        newPasswordInput = findViewById(R.id.newPasswordInput);
        confirmPasswordInput = findViewById(R.id.confirmPasswordInput);
        resetButton = findViewById(R.id.resetButton);
        loadingProgress = findViewById(R.id.loadingProgress);
    }

    private void setupToolbar() {
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setTitle(R.string.reset_password);
        }
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    }

    private void setupClickListeners() {
        resetButton.setOnClickListener(v -> attemptResetPassword());
    }

    private void attemptResetPassword() {
        // 重置错误提示
        usernameLayout.setError(null);
        phoneLayout.setError(null);
        newPasswordLayout.setError(null);
        confirmPasswordLayout.setError(null);

        // 获取输入内容
        String username = usernameInput.getText().toString().trim();
        String phone = phoneInput.getText().toString().trim();
        String newPassword = newPasswordInput.getText().toString();
        String confirmPassword = confirmPasswordInput.getText().toString();

        // 验证输入
        if (!validateInput(username, phone, newPassword, confirmPassword)) {
            return;
        }

        // 显示加载动画
        showLoading(true);

        try (DatabaseHelper db = new DatabaseHelper(this)) {
            // 验证用户名和手机号
            if (db.verifyUserPhone(username, phone)) {
                // 更新密码
                resetPassword(username, newPassword);
            } else {
                showLoading(false);
                Toast.makeText(ForgotPasswordActivity.this, 
                    getString(R.string.error_user_phone_not_match), 
                    Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean validateInput(String username, String phone, String newPassword, String confirmPassword) {
        if (TextUtils.isEmpty(username)) {
            usernameLayout.setError(getString(R.string.error_empty_username));
            return false;
        }

        if (TextUtils.isEmpty(phone)) {
            phoneLayout.setError(getString(R.string.error_empty_password));
            return false;
        }

        if (TextUtils.isEmpty(newPassword)) {
            newPasswordLayout.setError(getString(R.string.error_empty_password));
            return false;
        }

        if (newPassword.length() < 6) {
            newPasswordLayout.setError(getString(R.string.error_invalid_password));
            return false;
        }

        if (!newPassword.equals(confirmPassword)) {
            confirmPasswordLayout.setError(getString(R.string.error_passwords_not_match));
            return false;
        }

        return true;
    }

    private void resetPassword(String username, String newPassword) {
        DatabaseHelper db = new DatabaseHelper(this);
        
        // 先获取用户ID
        long userId = db.getUserId(username);
        
        if (userId != -1) {
            if (db.updatePassword(userId, newPassword)) {
                Toast.makeText(ForgotPasswordActivity.this,
                    getString(R.string.reset_success),
                    Toast.LENGTH_SHORT).show();
                finish();
            } else {
                showLoading(false);
                Toast.makeText(ForgotPasswordActivity.this,
                    getString(R.string.reset_failed),
                    Toast.LENGTH_SHORT).show();
            }
        } else {
            showLoading(false);
            Toast.makeText(ForgotPasswordActivity.this,
                "用户不存在",
                Toast.LENGTH_SHORT).show();
        }
        
        db.close();
    }

    private void showLoading(boolean show) {
        loadingProgress.setVisibility(show ? View.VISIBLE : View.GONE);
        resetButton.setEnabled(!show);
        usernameInput.setEnabled(!show);
        phoneInput.setEnabled(!show);
        newPasswordInput.setEnabled(!show);
        confirmPasswordInput.setEnabled(!show);
    }
} 